import { createApp } from "https://servestjs.org/@v1.1.9/mod.ts";

const app = createApp();

// SSE 路由
app.get("/sse", async (req) => {
    // 设置 SSE 响应头
    const headers = new Headers({
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
    });

    // 创建 SSE 响应
    const stream = new ReadableStream({
        async start(controller) {
            // 执行命令行命令
            const command = Deno.run({
                cmd: ["deno", "eval", "for (let i = 0; i < 10; i++) { console.log(`Message ${i}`); await new Promise(resolve => setTimeout(resolve, 1000)); }"],
                stdout: "piped",
                stderr: "piped",
            });

            // 读取命令输出并推送
            const decoder = new TextDecoder();
            for await (const chunk of command.stdout.readable) {
                const text = decoder.decode(chunk);
                controller.enqueue(new TextEncoder().encode(`data: ${text}\n\n`));
            }

            // 关闭流
            controller.close();
            command.close();
        },
    });

    // 返回 SSE 响应
    await req.respond({
        status: 200,
        headers,
        body: stream,
    });
});


app.get("/", async (req) => {
    const html = `
    <!DOCTYPE html>
    <html>
      <head>
        <title>Real-time Command Output</title>
      </head>
      <body>
        <h1>Real-time Command Output</h1>
        <pre id="output"></pre>
        <script>
          // 使用 EventSource 监听 SSE
          const eventSource = new EventSource("/sse");
          const output = document.getElementById("output");

          eventSource.onmessage = (event) => {
            output.textContent += event.data;
          };

          eventSource.onerror = () => {
            eventSource.close();
          };
        </script>
      </body>
    </html>
  `;

    await req.respond({
        status: 200,
        headers: new Headers({ "Content-Type": "text/html" }),
        body: html,
    });
});

// 启动服务器
app.listen({
    port: 8000,
});
